import axios from "axios";
import { ref } from "vue";
import { HWMI_URLS } from "../../modules/Api";

// 6-MP..药品	药品\可治疗\疾病	小儿克罗恩病..疾病
function checkSingleTripletFormat(text) {
    return text.match(/^.+\.\..+\t.+\\.+\\.+\t.+\.\..+$/) !== null;
}

export default function ({ emit }, { successEvent, errorEvent }) {
    const tripletText = ref("");
    const isUploadLoadingShow = ref(false);
    const isDirectUploadLoadingShow = ref(false);
    const tripletErrorLineNumbers = ref([]);

    const onSelectFileClick = () => {
        document.getElementById("in-import-file").click();
    };

    const onDirectUploadFileClick = () => {
        document.getElementById("in-direct-upload-file").click();
    }

    const onImportFileChange = e => {
        if (e.target.files.length === 0) {
            return;
        }

        const fileReader = new FileReader();
        fileReader.readAsText(e.target.files[0]);
        fileReader.onload = res => {
            tripletText.value = res.target.result;
            // clear file value to ensure onchange will be triggered again
            // if we load the same file next time.
            document.getElementById("in-import-file").value = "";
        }
    };

    const onDirectUploadFileChange = e => {
        if (e.target.files.length === 0) {
            return;
        }

        isDirectUploadLoadingShow.value = true;

        const fileReader = new FileReader();
        fileReader.readAsText(e.target.files[0]);
        fileReader.onload = res => {
            axios.post(HWMI_URLS.managementUrls.graphDbManagementUrls.directUploadUrl, {
                text:res.target.result
            })
                .then(res1 => {
                    if (res1.data.success) {
                        emit(successEvent, `成功导入文件`);
                    }
                    else {
                        emit(errorEvent, res1.data.message);
                    }
                })
                .catch(reason => {
                    console.log(reason);
                    emit(errorEvent, reason);
                })
                .finally(() => {
                    isDirectUploadLoadingShow.value = false;
                });
            // clear file value to ensure onchange will be triggered again
            // if we load the same file next time.
            document.getElementById("in-direct-upload-file").value = "";
        }
    };

    const uploadTriplets = () => {
        const errorLineNumbers = [];
        // 将换行符统一为"\n"
        const tripletLines = tripletText.value
            .replaceAll("\r\n", "\n")
            .replaceAll("\r", "\n")
            .split("\n");
        
        for (let i = 0; i < tripletLines.length; i++){
            if (!checkSingleTripletFormat(tripletLines[i])) {
                errorLineNumbers.push(i + 1);
            }
        }
        
        if (errorLineNumbers.length !== 0) {
            tripletErrorLineNumbers.value = errorLineNumbers;
            emit(errorEvent,
                `第${errorLineNumbers[0]}行等共${errorLineNumbers.length}行格式非法`);
            return;
        }

        tripletErrorLineNumbers.value = [];
        isUploadLoadingShow.value = true;

        axios.post(HWMI_URLS.managementUrls.graphDbManagementUrls.importUrl, {
            tripletLines
        })
            .then(res => {
                if (res.data.success) {
                    emit(successEvent, `成功导入${tripletLines.length}行数据`);
                }
                else {
                    emit(errorEvent, res.data.message);
                }
            })
            .catch(reason => {
                console.log(reason);
                emit(errorEvent, reason);
            })
            .finally(() => {
                isUploadLoadingShow.value = false;
            });
    };

    return {
        tripletText,
        onSelectFileClick,
        onDirectUploadFileClick,
        onImportFileChange,
        onDirectUploadFileChange,
        uploadTriplets,
        tripletErrorLineNumbers,
        isUploadLoadingShow,
        isDirectUploadLoadingShow
    };
}